<template>
  <div class="map-container">
    <el-input v-model="searchText" placeholder="请输入地点名称" class="search-input" v-if="!disable">
      <template #suffix>
        <el-button type="primary" style="margin-top: 5px; margin-bottom: 5px" @click="handleSearch"> 搜索 </el-button>
      </template>
    </el-input>
    <div id="map-container" ref="mapContainer"></div>
    <!-- 搜索结果下拉框 -->
    <!-- <el-select
      v-if="searchResults.length > 0"
      v-model="selectedResult"
      filterable
      placeholder="请选择地点"
      @change="handleSelectChange"
      class="result-select"
    >
      <el-option v-for="item in searchResults" :key="item.id" :label="item.name" :value="item.id">
        <div class="result-item">
          <div class="name">{{ item.name }}</div>
          <div class="address">{{ item.address }}</div>
        </div>
      </el-option>
    </el-select> -->
  </div>
</template>

<script lang="ts" setup>
import { defineComponent, ref, onMounted, onUnmounted } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';

// 类型定义
interface PositionInfo {
  id: string;
  name: string;
  address: string;
  location: [number, number];
}

const props = defineProps({
  selMarker: {
    type: Array,
    required: true
  },
  markers: {
    type: Array, //多个电子围栏
    required: true
  },
  disable: {
    type: Boolean,
    default: true,
    required: false
  }
});

const emit = defineEmits(['change']);

const mapContainer = ref<HTMLElement | null>(null);
const map = ref<AMap.Map | null>(null);
const AMap = ref<any>(null);
const markers = ref<AMap.Marker[]>([]);
const placeSearch = ref<AMap.PlaceSearch>(null);
const searchText = ref('');
const currentPosition = ref<[number, number] | null>(null);
const searchResults = ref<PositionInfo[]>([]);
const selectedResult = ref('');

// 初始化地图
const initMap = async () => {
  try {
    window._AMapSecurityConfig = {
      securityJsCode: 'f7c8191435e393805347c55b93338e57'
    };

    AMap.value = await AMapLoader.load({
      key: '479bb68a292209b4f9649f91b1427c46', // 替换为你的key
      version: '2.0',
      plugins: ['AMap.PlaceSearch', 'AMap.Geocoder']
    });

    if (mapContainer.value) {
      map.value = new AMap.value.Map(mapContainer.value, {
        viewMode: '2D',
        zoom: 15,
        center: [120.53535, 31.16828]
      });
    }
    placeSearch.value = new AMap.value.PlaceSearch({
      pageSize: 10,
      city: '苏州市',
      map: map.value,
      panel: undefined
    });
  } catch (error) {
    console.error('地图加载失败:', error);
    status.value = '地图加载失败，请检查Key配置';
  }

  // 点击地图添加标记
  map.value.on('click', (e: AMap.MapEvent) => {
    const position: [number, number] = [e.lnglat.getLng(), e.lnglat.getLat()];

    addMarker(position);

    currentPosition.value = position;
    emit('change', currentPosition.value);
  });
};

// 处理搜索
const handleSearch = () => {
  if (!searchText.value.trim()) {
    ElMessage.warning('请输入搜索内容');
    return;
  }

  placeSearch.value?.search(searchText.value, (status: string, result: any) => {
    if (status === 'complete' && result.poiList?.pois) {
      // searchResults.value = result.poiList.pois.map((poi: any) => ({
      //   id: poi.id,
      //   name: poi.name,
      //   address: poi.address,
      //   location: [poi.location?.lng, poi.location?.lat]
      // }));
    } else {
      ElMessage.error('搜索失败或没有结果');
      searchResults.value = [];
    }
  });
};

// 显示标记
const showMarkerList = (v: Array) => {
  if (!map.value) return;

  // 清除之前的标记
  clearMarkers();

  v.forEach((singleMarker) => {
    console.log('marker------', JSON.parse(singleMarker)[0]);
    const marker = new AMap.value.Marker({
      position: new AMap.value.LngLat(JSON.parse(singleMarker)[0], JSON.parse(singleMarker)[1]),
      map: map.value
    });

    markers.value.push(marker);
  });

  // let arrayPo = JSON.parse(position);
  // // 创建新标记
  // const marker = new AMap.value.Marker({
  //   position: new AMap.value.LngLat(arrayPo[0], arrayPo[1]),
  //   map: map.value
  // });

  // markers.value.push(marker);
};
// 显示标记
const showMarker = (position: [number, number]) => {
  if (!map.value) return;

  // 清除之前的标记
  clearMarkers();

  let arrayPo = JSON.parse(position);
  // 创建新标记
  const marker = new AMap.value.Marker({
    position: new AMap.value.LngLat(arrayPo[0], arrayPo[1]),
    map: map.value
  });

  markers.value.push(marker);
};
// 添加标记
const addMarker = (position: [number, number]) => {
  if (!map.value) return;

  // 清除之前的标记
  clearMarkers();

  // 创建新标记
  const marker = new AMap.value.Marker({
    position: new AMap.value.LngLat(position[0], position[1]),
    map: map.value
  });

  markers.value.push(marker);
};

// 清除所有标记
const clearMarkers = () => {
  markers.value.forEach((marker) => {
    marker.setMap(null);
  });
  markers.value = [];
};

watch(
  () => props.selMarker,
  (v: Array) => {
    showMarker(v);
  },
  { immediate: true }
);

watch(
  () => props.markers,
  (v: Array) => {
    showMarkerList(v);
  },
  { immediate: true }
);

onMounted(async () => {
  try {
    initMap();
  } catch (error) {
    console.error('Failed to load AMap:', error);
  }
});

onUnmounted(() => {
  if (map.value) {
    map.value.destroy();
    map.value = null;
  }
});
</script>

<style scoped>
#map-container {
  width: 100%;
  height: 500px;
}

.position-info {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}
</style>
